<template>
  <div class="flexContent">
    <div class="searchBox">
      <el-form ref="formRef" class="demo-form-inline" @submit.native.prevent label-position="left" label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="规则名称">
                  <el-input v-model="name" style="width: 95%" placeholder="请输入..." clearable
                    @keyup.enter.native="searchFn" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="btnBox">
            <el-button @click.stop="searchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button @click.stop="resetFn" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <div class="add">
      <el-button class="addBtn" @click="addFn">新增</el-button>
    </div>
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;">
        <vxe-table :column-config="{ resizable: true }" class="tablebox" border ref="xTable1"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="100%"
          align="center">
          <vxe-column type="seq" title="序号" width="80"></vxe-column>
          <vxe-column field="name" title="规则名称" />
          <vxe-column field="updateCycle" title="更新周期">
            <template v-slot="{ row }">
              {{ row.updateCycle === "0" ? "每天" : "" }}
            </template>
          </vxe-column>
          <vxe-column title="涨幅区间">
            <template v-slot="{ row }">
              {{ row.minRise }} 至 {{ row.maxRise }}
            </template>
          </vxe-column>
          <vxe-column field="imgUrl" title="有效期">
            <template v-slot="{ row }">
              {{ row.startDate | parseTime }} 至 {{ row.endDate | parseTime }}
            </template>
          </vxe-column>
          <vxe-column title="状态">
            <template v-slot="{ row }">
              <el-tag v-if="row.status === '0'" disabled type="primary" plain>使用中</el-tag>
              <el-tag v-if="row.status === '1'" disabled type="info" plain>已禁用</el-tag>
            </template>
          </vxe-column>
          <vxe-column title="操作" fixed="right" width="150">
            <template v-slot="{ row }">
              <el-button slot="reference" style="color: rgb(0, 132, 255); margin-right: 10px" type="text" size="big"
                @click.stop="edit(row)">修改</el-button>
              <el-button type="text" size="big" style="margin-right: 10px; color: red"
                @click="$delFn('记录', del, row)">删除</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,->, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <AddDialog :close-on-click-modal="false" :is-show-btn="isShowBtn" :show-dialog.sync="showDialog" :width="width"
      :title="title" @btnOk="btnOk" @close="close">
      <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="110px">
        <el-form-item label="规则名称" style="width: 100%" prop="name">
          <el-input v-model="addForm.name" style="width: 90%" />
        </el-form-item>
        <el-form-item label="更新周期" style="width: 100%" prop="updateCycle">
          <el-radio v-model="addForm.updateCycle" label="0">每天</el-radio>
        </el-form-item>
        <el-row :gutter="24" style="padding: 0" type="flex" justify="start">
          <el-col :span="11" :offset="0">
            <el-form-item label="涨幅区间" style="width: 100%" prop="minRise">
              <el-input v-model="addForm.minRise" />
            </el-form-item>
          </el-col>
          <el-col :span="1" :offset="0">
            <p>至</p>
          </el-col>
          <el-col :span="8" style="padding: 0" :offset="1">
            <el-form-item style="width: 100%" prop="maxRise" label-width="0px">
              <el-input v-model="addForm.maxRise" style="width: 70%" />
              <span>{{ $tokenName }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="有效期" style="width: 100%" prop="endDate">
          <el-date-picker v-model="dateList" type="daterange" range-separator="-" unlink-panels start-placeholder="开始日期"
            end-placeholder="结束日期" style="width: 90%" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd"
            @change="dateChange" />
        </el-form-item>
        <el-form-item :label="$tokenName + '状态'" style="width: 100%" prop="status">
          <el-radio-group v-model="addForm.status">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </AddDialog>
  </div>
</template>

<script>
import { parseTime3 } from "@/utils";
import AddDialog from "@/components/Goods/AddDialog";
import { getStockList, addStock, updateStock, delStock } from "@/api/h5";
export default {
  name: "StockInfo",
  components: {
    AddDialog,
  },
  filters: {
    parseTime(val) {
      return parseTime3(val);
    },
  },
  data() {
    return {
      isShowBtn: false,
      width: "50%",
      title: "添加商品",
      showDialog: false,
      name: "",
      addForm: {
        name: "",
        startDate: "",
        endDate: "",
        // rise: '',
        maxRise: "",
        minRise: "",
        status: "",
        updateCycle: "",
      },
      dateList: [],
      addRules: {
        name: [
          {
            required: true,
            message: "请输入规则名称",
            trigger: ["blur", "change"],
          },
          {
            min: 1,
            max: 15,
            message: "长度在1到15个字符",
            trigger: ["blur", "change"],
          },
          {
            pattern: /^[^\’\<\>\%\&\{\}\￥\@\$\'\"\【\】\\\/\ ]*$/,
            message: "不能输入特殊字符",
            trigger: ["blur", "change"],
          },
        ],
        updateCycle: [
          {
            required: true,
            message: "请选择更新周期",
            trigger: ["blur", "change"],
          },
        ],
        // rise: [{
        //   required: true,
        //   // validator: this.rulesList,
        //   message: '请输入涨幅',
        //   trigger: ['blur', 'change']
        // }],
        minRise: [
          {
            required: true,
            // validator: this.rulesList,
            message: "请输入涨幅",
            trigger: ["blur", "change"],
          },
          {
            pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
            message: "数字、支持两位小数",
            trigger: ["blur", "change"],
          },
        ],
        maxRise: [
          {
            required: true,
            // validator: this.rulesList,
            message: "请输入涨幅",
            trigger: ["blur", "change"],
          },
          {
            pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
            message: "数字、支持两位小数",
            trigger: ["blur", "change"],
          },
        ],
        startDate: [
          {
            required: true,
            message: "请输入有效期",
            trigger: ["blur", "change"],
          },
        ],
        endDate: [
          {
            required: true,
            message: "请输入有效期",
            trigger: ["blur", "change"],
          },
        ],
        status: [
          {
            required: true,
            message: "请选择状态",
            trigger: ["blur", "change"],
          },
        ],
      },
      isSearch: false,
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      stockList: [],
      id: "",
    };
  },
  created() {
    this.getStockList();
  },
  methods: {
    async getStockList() {
      if (!this.isSearch) {
        this.name = "";
      }
      const res = await getStockList({ ...this.page, name: this.name });
      if (res.code === 200) {
        const result = res.data;
        this.stockList = result.list;
        this.page.pageSize = result.pageSize;
        this.page.pageNum = result.pageNum;
        this.page.total = result.total;
        console.log("stockList", this.stockList);
        const $table = this.$refs.xTable1
        $table.loadData(this.stockList);
      } else {
        // this.$message.error(res.message);
      }
    },
    async searchFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = true;
      this.getStockList();
    },
    resetFn() {
      this.name = "";
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = false;
      this.getStockList();
    },
    addFn() {
      this.title = "添加商品";
      this.showDialog = true;
    },
    async del(row) {
      const res = await delStock({ id: row.id });
      if (res.code === 200) {
        this.$message.success("删除成功");
        if (this.stockList.length === 1 && this.page.pageNum > 1)
          this.page.pageNum--;
        this.getStockList();
      } else {
        // this.$message.error(res.message);
      }
    },
    dateChange(val) {
      // console.log(val)
      this.addForm.startDate = val[0];
      this.addForm.endDate = val[1];
      // console.log(this.addForm)
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      this.getStockList();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      this.page.pageNum = val;
      this.getStockList();
    },

    close() {
      this.showDialog = false;
      this.addForm = {
        name: "",
        startDate: "",
        endDate: "",
        // rise: '',
        maxRise: "",
        minRise: "",
        status: "",
        updateCycle: "",
      };
      this.dateList = [];
      this.$refs.addFormRef.resetFields();
    },
    btnOk() {
      // 判断是新增还是修改
      if (this.title === "添加商品") {
        // 新增
        this.$refs.addFormRef.validate(async (isOk) => {
          if (isOk) {
            //
            const res = await addStock(this.addForm);
            if (res.code === 200) {
              this.$message.success("新增成功");
              this.getStockList();
              this.close();
            } else {
              // this.$message.error(res.message);
            }
          } else {
            this.$message.warning("请检查输入信息");
          }
        });
      } else if (this.title === "修改") {
        // 修改
        this.$refs.addFormRef.validate(async (isOk) => {
          if (isOk) {
            const res = await updateStock({ ...this.addForm, id: this.id });
            if (res.code === 200) {
              this.$message.success("修改成功");
              this.getStockList();
              this.close();
            } else {
              // this.$message.error(res.message);
            }
          } else {
            this.$message.warning("请检查输入信息");
          }
        });
      }
    },
    edit(row) {
      this.showDialog = true;
      this.title = "修改";
      console.log(row);
      this.id = row.id;
      this.addForm.name = row.name;
      this.addForm.maxRise = row.maxRise;
      this.addForm.status = row.status;
      this.addForm.minRise = row.minRise;
      this.addForm.updateCycle = row.updateCycle;
      this.addForm.endDate = parseTime3(row.endDate);
      this.addForm.startDate = parseTime3(row.startDate);
      this.dateList.push(parseTime3(row.startDate));
      this.dateList.push(parseTime3(row.endDate));
    },
  },
};
</script>

<style scoped lang="scss">
.imgUpload {
  ::v-deep .el-upload:hover {
    border-color: #409eff;
  }

  ::v-deep .el-upload {
    position: relative;
    margin-bottom: 10px;
    margin-left: 5px;
    width: 70px;
    height: 70px;
    line-height: 30px;
    padding-top: 5px;
  }

  .txt {
    color: #595858;
    font-size: 12px;
  }
}

.el-upload--picture-card i {
  font-size: 12px !important;
}
</style>
